﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;

namespace E0XPayService.Utils
{
    public class StringExtension
    {
        private static Int64 seed = Int64.Parse(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds.ToString("0"));

        /// <summary>
        /// 获取外网IP
        /// </summary>
        /// <returns></returns>
        public static string GetHostAddress()
        {
            var userHostAddress = HttpContext.Current.Request.UserHostAddress;

            if (string.IsNullOrEmpty(userHostAddress))
            {
                userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }

            if (string.IsNullOrEmpty(userHostAddress))
            {
                userHostAddress = HttpContext.Current.Request.UserHostAddress;
            }
            //最后判断获取是否成功，并检查IP地址的格式（检查其格式非常重要）
            if (string.IsNullOrEmpty(userHostAddress) || !IsIP(userHostAddress))
            {
                userHostAddress = "127.0.0.1";
            }

            return userHostAddress;
        }
    
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static string GetPrimaryKey()
        {
            return Interlocked.Increment(ref seed).ToString();
        }

        /// <summary>
        /// 检查IP地址格式
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>  
        private static bool IsIP(string ip)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }
    }

    public enum TradeType
    {
        /// <summary>
        /// 微信扫码(对应支付)
        /// </summary>
        Wx_NATIVE,
        /// <summary>
        /// 微信公众号(对应先付)
        /// </summary>
        Wx_JSAPI,
        /// <summary>
        /// 支付宝扫码
        /// </summary>
        Ali_NATIVE,
        /// <summary>
        /// 支付宝先付
        /// </summary>
        Ali_JSAPI
    }
}